package org.jeecg.common.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

import lombok.extern.slf4j.Slf4j;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTcPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STMerge;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STVerticalJc;

/**
 * 导出word
 * @author ygc
 */
@Slf4j
public class MSWordTool {

    //文件夹地址
    public static String fileUrl = "F:\\common//";

    public static void main(String[] args) throws IOException, InvalidFormatException {
        //创建文件夹
        String newfileUrl = MSWordTool.createFile("first1");
        List<String> images = new ArrayList<>();
        WordVO wordVO = new WordVO();
        wordVO.setOutTilePath(newfileUrl + "//bingli.doc");
        wordVO.setAge("21");
        wordVO.setName("ces");
        wordVO.setImages(images);
        //下载图片到服务器
        String imageurl = MSWordTool.downImage("https://dayizhihui.oss-cn-beijing.aliyuncs.com/common/yujunggao1.png",1,newfileUrl);
        images.add(imageurl);
        //从服务器下载图片，并形成word
        MSWordTool.outTilePath(wordVO);
        //文件压缩为zip
        String zipUrl = fileUrl + "/" + new Date().getTime()+".zip";
        ZipUtils.createZip(newfileUrl, zipUrl);

    }
    //下载图片
    public static String downImage(String imageUrl, int i, String newfileUrl){
        String filename = "";
        try {
            // 构造URL
            URL url = new URL(imageUrl);
            // 打开连接
            URLConnection con = url.openConnection();
            // 输入流
            InputStream is = con.getInputStream();
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;
            // 输出的文件流
            filename = newfileUrl + "/" + i + ".png";  //下载路径及下载图片名称
            File file = new File(filename);
            FileOutputStream os = new FileOutputStream(file, true);
            // 开始读取
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            System.out.println("下载图片：" + i);
            // 完毕，关闭所有链接
            os.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return filename;
    }
    //创建文件夹
    public static String createFile(String fileName){
        String url = fileUrl + "//"+ fileName;
        File file=new File(url);
        if(!file.exists()){//如果文件夹不存在
            file.mkdir();//创建文件夹
        }
        log.info("创建文件夹：" + url);
        return url;
    }

    //导出word
    public static String outTilePath(WordVO wordVO){
        String outTilePath = wordVO.getOutTilePath();
        XWPFDocument doc = new XWPFDocument();
        XWPFParagraph para;
        XWPFRun run;
        //创建表格
        XWPFTable table  = doc.createTable(5,4);
        table.setCellMargins(3, 5, 3, 5);
//        table.addNewCol();//添加新列
//        table.createRow();//添加新行
        String[] title1 = new String[]{"姓名"," ","性别"," "};
        String[] title2 = new String[]{"年龄"," ","是否首诊"," "};
        title1[1] = wordVO.getName();
        title1[3] = wordVO.getSex()=="1"?"男":"女";
        title2[1] = wordVO.getAge();
        title2[3] = wordVO.getIsFirst()=="0"?"首诊":"复诊";
        XWPFTableRow row;
        XWPFTableCell cell;
        CTTcPr cellPr;
        for(int j=0;j<5;j++){
            row = table.getRow(j);
            row.setHeight(600);
            //第一行
            for(int i=0;i<title1.length;i++){
                //创建单元格
                cell = row.getCell(i);
                //单元格属性
                cellPr = cell.getCTTc().addNewTcPr();
                //设置宽度
                cellPr.addNewTcW().setW(BigInteger.valueOf(5000));
                //垂直居中
                cellPr.addNewVAlign().setVal(STVerticalJc.CENTER);
                //第一个段落
                para = cell.getParagraphs().get(0);
                //设置对齐方式
                para.setAlignment(ParagraphAlignment.CENTER);
                //段落的对齐方式 1左 2中 3右 4往上 左 不可写0和负数
                para.setFontAlignment(2);
                //一个XWPFRun代表具有相同属性的一个区域：一段文本
                run = para.createRun();
                //设置字体
                run.setFontFamily("仿宋");
                //设置字体大小
                run.setFontSize(11);
                if(j==0) {
                    //字体宽
//                    run.setBold(true);
                    run.setText(title1[i]);
                }
            }
            //第二行
            if(j==1){
                for(int y=0;y<4;y++){
                    if(y==0) {
                        cell = row.getCell(0);
                        cellPr = cell.getCTTc().addNewTcPr();
                        cellPr.addNewTcW().setW(BigInteger.valueOf(5000));
                        para = cell.getParagraphs().get(0);
                        para.setAlignment(ParagraphAlignment.CENTER);
                        para.setFontAlignment(2);
                        run = para.createRun();
                        run.setFontFamily("仿宋");
                        run.setFontSize(13);
                        run.setText("手机号");
                    }
                    if(y==1) {
                        cell = row.getCell(y);
                        cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
                        cell.setText(wordVO.getPhone());
                    }else {
                        cell = row.getCell(y);
                        cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
                        cell.setText(wordVO.getPhone());
                    }
                }


            }
            if(j==2){
                for(int y=0;y<4;y++){
                    if(y==0) {
                        cell = row.getCell(0);
                        cellPr = cell.getCTTc().addNewTcPr();
                        cellPr.addNewTcW().setW(BigInteger.valueOf(5000));
                        para = cell.getParagraphs().get(0);
                        para.setAlignment(ParagraphAlignment.CENTER);
                        para.setFontAlignment(2);
                        run = para.createRun();
                        run.setFontFamily("仿宋");
                        run.setFontSize(13);
                        run.setText("身份证号");
                    }
                    if(y==1) {
                        cell = row.getCell(y);
                        cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
                        cell.setText(wordVO.getIdCard());
                    }else {
                        cell = row.getCell(y);
                        cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
                        cell.setText(wordVO.getIdCard());
                    }


                }
            }

            for(int i=0;i<title2.length;i++){
                cell = row.getCell(i);
                cellPr = cell.getCTTc().addNewTcPr();
                cellPr.addNewTcW().setW(BigInteger.valueOf(5000));
                para = cell.getParagraphs().get(0);
                para.setAlignment(ParagraphAlignment.CENTER);
                para.setFontAlignment(2);
                run = para.createRun();
                run.setFontFamily("仿宋");
                run.setFontSize(13);
                if(j==3) {

                    run.setText(title2[i]);
                }
            }
            if(j==4){
                for(int y=0;y<4;y++){
                    if(y==0) {
                        cell = row.getCell(0);
                        //单元格属性
                        cellPr = cell.getCTTc().addNewTcPr();
                        //设置宽度
                        cellPr.addNewTcW().setW(BigInteger.valueOf(5000));
                        //第一个段落
                        para = cell.getParagraphs().get(0);

                        //设置对齐方式
                        para.setAlignment(ParagraphAlignment.CENTER);
                        //居中
                        para.setFontAlignment(2);

                        run = para.createRun();
                        run.setFontFamily("仿宋");
                        run.setFontSize(13);
                        run.setText("病情描述");
                    }
                    if(y==1) {
                        cell = row.getCell(y);
                        cell.setText(wordVO.getDesction());
                        cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
                    }else {
                        cell = row.getCell(y);

                        cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
                    }
                }

            }
        }
        if(wordVO.getImages().size() > 0){
            int j = 0;
            //创建表格
            XWPFTable table1  = doc.createTable(wordVO.getImages().size(),4);
            for (String imgPath: wordVO.getImages() ) {

                XWPFTableRow row1;
                XWPFTableCell cell1;
                CTTcPr cellPr1;
                row1 = table1.getRow(j);
                for(int i = 0; i < 4 ;i++) {
                    if (i == 0){
                        row1.getCell(i).getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
                    } else {
                        row1.getCell(i).getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
                    }
                }
                cell1 = row1.getCell(0);
                cell1.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
                List<XWPFParagraph> paragraphs1 = cell1.getParagraphs();
                XWPFParagraph newPara1 = paragraphs1.get(0);
                XWPFRun imageCellRunn1 = newPara1.createRun();
                File image = new File(imgPath);
                try (FileInputStream is = new FileInputStream(imgPath)) {
                    imageCellRunn1.addPicture(is, XWPFDocument.PICTURE_TYPE_JPEG, image.getName(), Units.toEMU(460), Units.toEMU(460)); // 200x200 pixels
                }catch (Exception e){
                    e.printStackTrace();
                }
                j++;
            }
        }

        try {
            OutputStream os = new FileOutputStream(outTilePath);
            doc.write(os);
            if(os!=null){
                try{
                    os.close();
                    System.out.println("文件已输出！");
                    log.info("导出word：" + wordVO.getOutTilePath());
                }
                catch(IOException e){
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return outTilePath;
    }
}